<template>
  <div class="mynavbar_container">
    <el-row>
      <el-col :span="16" :offset="4">
        <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            @select="handleSelect"
            background-color="#336699"
            text-color="#fff"
            active-text-color="#ffd04b">
          <div class="mynavbar_logo_div">
            <a href="/"><img class="mynavbar_logo_img"
                             src="https://img.simoniu.com/vue_logo_200px.png"/>&nbsp;网站名称</a>
          </div>
          <el-menu-item index="1">主选项1</el-menu-item>
          <el-submenu index="2">
            <template slot="title">主选项2</template>
            <el-menu-item index="2-1">选项2-1</el-menu-item>
            <el-menu-item index="2-2">选项2-2</el-menu-item>
            <el-menu-item index="2-3">选项2-3</el-menu-item>
          </el-submenu>
          <el-menu-item index="3">主选项3</el-menu-item>
          <el-submenu index="case">
            <template slot="title">案例4</template>
            <el-menu-item index="/case/session">前端session案例</el-menu-item>
            <el-menu-item index="4-2">选项4-2</el-menu-item>
            <el-menu-item index="4-3">选项4-3</el-menu-item>
          </el-submenu>
          <el-menu-item index="5">主选项5</el-menu-item>
          <el-submenu index="users" class="el-submenu-userinfo" v-if="isLogin">
            <template slot="title">
              <el-avatar :size="28"
                         :src="currentLoginUserInfo.avatar"></el-avatar>
              用户名 {{ currentLoginUserInfo.username.substring(0, 6) }}
            </template>
            <el-menu-item index="/users/center"><i class="el-icon-user"></i>个人中心</el-menu-item>
            <el-menu-item index=""><i class="el-icon-shopping-cart-1"></i>我的订单</el-menu-item>
            <el-menu-item index=""><i class="el-icon-star-off"></i>我的收藏</el-menu-item>
            <el-menu-item @click="logout"><i class="el-icon-back"></i>注&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;销
            </el-menu-item>
          </el-submenu>
          <div class="mynavbar_login_div" v-if="!isLogin">
            <router-link to="/login">登录</router-link>
          </div>
        </el-menu>
      </el-col>
    </el-row>
  </div>
</template>

<script>

import {isLogin, logout} from "@/api/users/users";
// 完整引入outils工具类
const outils = require('outils');
export default {
  name: "MyNavBar",
  data() {
    return {
      isLogin: false, //默认未登录
      activeIndex: '1',
      currentLoginUserInfo: this.$store.state.loginSuccessUser
    };
  },
  mounted() {
    if (this.$store.state.loginFlag === null) {
      this.initLoginStatus();
    }
    console.log("--------在mounted中判断this.$store.state.loginFlag的状态---------");
    console.log(this.$store.state.loginFlag);
    this.isLogin = this.$store.state.loginFlag;
    console.log("this.isLogin===>" + this.isLogin);
  },

  methods: {
    async initLoginStatus() {
      console.log("------------初始化登录状态，准发发送异步请求！！！---------------")
      let result = await isLogin().then(resp => {
        if (resp.data.code === 200) {

          let obj = resp.data.data;
          obj.tokenName = "";
          obj.tokenValue = "";
          obj.password = "";
          localStorage.setItem("currentLoginUserInfo",JSON.stringify(obj));
          this.currentLoginUserInfo = JSON.parse(localStorage.getItem("currentLoginUserInfo"));

          return true;

        }else{
          return false;
        }

      });
      console.log("--------判断是否已经登录----------")
      console.log(result);
      //通过dispatch修改state
      //this.$store.dispatch("actionInitLoginFlag",result);
      //直接修改state,官方并不推荐
      //this.$store.state.loginFlag=result;
      //通过commit修改
      this.$store.commit("initLoginFlag", result);

      sessionStorage.setItem("currentLoginStatus", result);
      console.log("----------vuex中的loginFlag-----------")
      console.log(this.$store.state.loginFlag);
      this.isLogin = this.$store.state.loginFlag;
    },

    handleSelect(key, keyPath) {
      //console.log(key, keyPath);
      console.log(keyPath);
      //this.$router.push({ path: keyPath[1]});
      //this.$router.replace(keyPath[1]);
      if (keyPath.length === 1) {
        //window.location.href=keyPath[0];
        this.$router.push({path: keyPath[0]}).catch(() => {
        });
        this.activeIndex = keyPath[0];
      } else {
        this.$router.push({path: keyPath[1]}).catch(() => {
        });
        //window.location.href=keyPath[1];
        this.activeIndex = keyPath[1];
      }
    },
    goHome() {
      //返回到网站的首页
      this.$router.push({path: '/'});
      //this.$router.replace({path:'/'});
    },
    logout() {
      //console.log('执行用户注销....')
      logout().then(resp => {
        if (resp.data.code === 200) {
          this.$message.success("注销成功！");
          //把cookie里保存的token信息清除掉。清除session保存用户资料
          //跳转到登录页面
          outils.removeCookie("satoken");
          localStorage.removeItem("currentLoginUserInfo");
          //this.$store.dispatch("actionInitLoginFlag",null);
          //this.$store.state.loginFlag=null;
          this.$store.commit("initLoginFlag", null);

          sessionStorage.removeItem("currentLoginStatus");
          //起一个定时器
          setTimeout(() => {
            window.location.href = '/login'
          }, 1000);

        }
      })
    }
  }
}
</script>

<style scoped>

.mynavbar_container {
  width: 100%;
  margin: 0 auto;
  background-color: #336699;
  /*导航栏固定在页面顶部*/
  top: 0;
  left: 0;
  z-index: 200 !important;; /*这个值不要设置太大，否则会遮盖messagebox*/
  position: fixed;
}

.mynavbar_logo_div {
  float: left;
  width: 120px;
  height: 60px;
  vertical-align: middle;
  color: #ffffff;
}

.mynavbar_logo_div a {
  color: #ffffff;
  text-decoration: none;
  font-size: 12pt;
}

.mynavbar_login_div {
  float: right;
  width: 120px;
  height: 60px;
  line-height: 60px;
  vertical-align: middle;
  color: #ffffff;
  text-align: left;
}

.mynavbar_login_div a {
  color: #ffffff;
  text-decoration: none;
  font-size: 10pt;
}

.mynavbar_logo_img {
  margin: 18px 0px;
  width: 32px;
  height: 32px;
  display: inline;
  vertical-align: middle;
}

.el-menu-item, .el-submenu {
  width: 120px;
  text-align: center;
}

.el-submenu-userinfo {
  width: 200px;
  text-align: center;
}


.el-menu-item a {
  text-decoration: none;
}

.el-menu--horizontal .el-menu .el-menu-item {
  width: 200px;
  text-align: center;
}
</style>